﻿using System;
using System.Collections.Generic;

namespace Core
{
    public class DSStruct : DSVar, IBindDBVar
    {
        private readonly Dictionary<string, DSVar> dict = new();

        public void Add(string name, DSVar v)
        {
            dict.TryAdd(name, v);
        }

        public DSVar Find(string source)
        {
            var idx = source.IndexOf(".", StringComparison.Ordinal);
            DSVar ele = null;
            if (idx == -1)
            {
                ele = GetVar(source);
            }
            else
            {
                var key = source[..idx];
                var s = GetStruct(key);
                if (s != null)
                {
                    ele = s.Find(source[(idx + 1)..]);
                }
            }
            return ele;
        }

        public DSVar GetVar(string name)
        {
            return dict.GetValueOrDefault(name);
        }

        public DSStruct GetStruct(string name)
        {
            return dict.TryGetValue(name, out var value) == false ? null : value as DSStruct;
        }
    }
}
